<?php
/**
 * 运费补贴计算 (运行一次即可)
 *
 * 命令：
 * bash$ ./cli freefreights
 *
 * @author     楚吟风 <Chuyinfeng@gmail.com>
 */
class CLI_Freefreights extends CLI
{
    public function main()
    {
        // 记录开始时间
        $time_start = microtime(TRUE);
        // 记录初始内存
        $mem_start = memory_get_usage();


        $offset=0;
        $per_count=100;

        // 清空原有免运费表
        DB::delete('shop_free_freights')
            ->execute();

        //循环获取所有符合条件的订单
        while (true) {
            $rows = DB::select('shop_id','order_sn','order_id','created')
                ->from('orders')
                ->order_by('order_id', 'ASC')
                ->where('pay_time','>',strtotime('2011-6-8'))
                ->where('pay_time','<',strtotime('2011-6-22'))
                ->where('end_time','>',strtotime('2011-6-8'))
                ->where('end_time','<',strtotime('2011-6-29'))
                ->where('order_status','=','TRADE_FINISHED')
                ->where('order_amount','>','499')
                ->limit($per_count)
                ->offset($offset)
                ->fetch_all();

            //记录集遍历完毕
            if(count($rows)<1){
                //计算脚本运行耗时
                $time_script = round( microtime(TRUE) - $time_start , 3);
                CLI::output("Done at:" . date('Y-m-d H:i:s') ." \n script time:" . $time_script.' mem:'.(memory_get_usage()-$mem_start));
                die();
            }

            //根据记录集进行计算
            $j=0;
            foreach($rows as $item){
                // 判断单品价格是否超过500
                $flag = DB::select(array(DB::expr("count(*)"),'c'))
                        ->from('order_goods')
                        ->where('order_id','=',$item['order_id'])
                        ->where('price','>','499')
                        ->fetch_one()>0?TRUE:FALSE;
                if ($flag)
                {
                    $j++;
                    DB::insert('shop_free_freights',
                            array(
                            'shop_id',
                            'order_sn',
                            'free_fee',
                            'created_time'
                            )
                        )
                        ->values(
                            array(
                            $item['shop_id'],
                            $item['order_sn'],
                            '20',
                            $item['created']
                            )
                        )
                        ->execute();

                    CLI::output  ($offset + $j . "   ,  " .  $item['shop_id'] . "    ,   "  . '20' . "    \n");
                }
            }

            $offset=$offset+$per_count;
        }





    }
}